package com.lc.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.auth.mapper.SysDeptMapper;
import com.lc.auth.service.SysDeptService;
import com.lc.common.utils.DeptHelper;
import com.lc.model.system.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author yqr
 * @since 2023-06-10
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public void saveDept(SysDept sysDept) {
        //获取父节点的treepath
        String treePath = sysDept.getTreePath();
        sysDeptMapper.insert(sysDept);
        String id = String.valueOf(sysDept.getId());
        treePath = treePath + id;
        sysDept.setTreePath(treePath);
        sysDeptMapper.updateById(sysDept);
    }

    @Override
    public String getParentName(SysDept sysDept) {
        String parentId = String.valueOf(sysDept.getParentId());
        SysDept sysDept1 = sysDeptMapper.selectById(parentId);
        return sysDept1.getName();
    }

    @Override
    public List<SysDept> getDeptTreeList() {
        //获取部门数据
        LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(SysDept::getSortValue);
        List<SysDept> sysDeptList = this.list(lqw);

        //判断数据是否为空
        if (CollectionUtils.isEmpty(sysDeptList)){
            return null;
        }
        //构建树型菜单
        return DeptHelper.buildTree(sysDeptList);
    }
}
